package com.zueb.web.servlet;

import com.alibaba.fastjson.JSON;
import com.zueb.pojo.Admin;
import com.zueb.pojo.Faculty;
import com.zueb.service.AdminService;
import com.zueb.service.FacultyService;
import com.zueb.service.impl.AdminServiceImpl;
import com.zueb.service.impl.FacultyServiceImpl;
import com.zueb.util.MD5;
import com.zueb.util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "AdminServlet", value = "/AdminServlet")
public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();
    private static String message = "";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //转发请求到doPost
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //转码
        request.setCharacterEncoding("UTF-8");
        //action表示用来区分是什么操作
        String action = request.getParameter("action");

        if (action.equals("adminLogin")) {
            adminLogin(request, response);  //管理员登录
        } else if (action.equals("adminLogout")) {
            adminLogout(request, response);  //退出登录
        } else if (action.equals("showAdmin")) {
            showAdmin(request, response);    //展示所有管理员信息
        } else if (action.equals("addAdminUi")) {
            addAdminUi(request, response);    //添加管理员
        } else if (action.equals("addAdmin")) {
            addAdmin(request, response);    //添加管理员
        } else if (action.equals("deleteAdmin")) {
            deleteAdmin(request, response);   //删除管理员账户
        } else if (action.equals("editAdminUi")) {
            editAdminUi(request, response);    //进入修改管理员账户页面
        } else if (action.equals("editAdmin")) {
            editAdmin(request, response);    //修改管理员账户
        } else if (action.equals("admin")) {
            admin(request, response);
        }
    }


    /**
     * 修改管理员账户
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void editAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        SessionUtils.isSession(request, response);
        //获取页面传来的数据
        Integer adminId = Integer.valueOf(request.getParameter("adminId"));
        String passWord = request.getParameter("passWord");
        String adminRole = request.getParameter("adminRole");
        Integer facultyId = Integer.valueOf(request.getParameter("faculty"));
        if (!passWord.equals("") && passWord != null) {
            passWord = MD5.md5(passWord);
        }
        //封装对象
        Admin editAdmin = new Admin();
        editAdmin.setAdminId(adminId);
        editAdmin.setPassword(passWord);
        editAdmin.setAdminRole(adminRole);
        editAdmin.setFacultyId(facultyId);
        //调用Service
        adminService.updateAdmin(editAdmin);

        response.getWriter().write("true");
//        message = "<script>self.opener.location.reload();window.close();window.opener.alert('修改成功！');</script>";
//        //把信息放入页面
//        request.setAttribute("message", message);
//        //跳转页面
//        request.getRequestDispatcher("message.jsp").forward(request, response);
    }

    /**
     * 进入修改管理员账户页面
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void editAdminUi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        SessionUtils.isSession(request, response);

        //获取该管理员账户的信息
        String adminName = request.getParameter("adminName");
        Admin editAdmin = adminService.getAdminByName(adminName);
        //获取学院列表
        FacultyService facultyService = new FacultyServiceImpl();
        List<Faculty> faculties = facultyService.getAllFaculty();
        //将信息放入页面
        request.setAttribute("admin", editAdmin);
        request.setAttribute("faculties", faculties);
        //跳转页面
        request.getRequestDispatcher("editAdmin.jsp").forward(request, response);

    }

    /**
     * 删除管理员账户
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void deleteAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        SessionUtils.isSession(request, response);
        Integer adminId = Integer.valueOf(request.getParameter("adminId"));
        adminService.deleteAdmin(adminId);

        response.getWriter().write("true");
//        message = "<script>alert('管理员删除成功!');window.open('AdminServlet?action=showAdmin','_self')</script>";
//        //把信息放入页面
//        request.setAttribute("message", message);
//        //跳转页面
//        request.getRequestDispatcher("message.jsp").forward(request, response);
    }

    /**
     * 添加管理员
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void addAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        SessionUtils.isSession(request, response);
        //获取页面传来的数据
        String adminName = request.getParameter("adminName");
        String passWord = request.getParameter("passWord");
        String adminRole = request.getParameter("adminRole");
        String facultyId = request.getParameter("faculty");
        //封装对象
        Admin addAdmin = new Admin();
        addAdmin.setAdminName(adminName);
        addAdmin.setPassword(MD5.md5(passWord));
        addAdmin.setAdminRole(adminRole);
        addAdmin.setFacultyId(Integer.parseInt(facultyId));
        //调用Service
        Admin admin1 = adminService.getAdminByName(adminName);
        //判断管理员账户是否存在
        if (admin1 == null) {
            //管理员不存在则添加
            adminService.addAdmin(addAdmin);
            response.getWriter().write("true");
        } else {
            response.getWriter().write("false");
        }
//        //把信息放入页面
//        request.setAttribute("message", message);
//        //跳转页面
//        request.getRequestDispatcher("message.jsp").forward(request, response);
    }

    /**
     * 添加管理员的界面
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void addAdminUi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        SessionUtils.isSession(request, response);
        //获取学院列表
        FacultyService facultyService = new FacultyServiceImpl();
        List<Faculty> faculties = facultyService.getAllFaculty();

        String jsonString = JSON.toJSONString(faculties);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(jsonString);
        //将列表放入页面
//        request.setAttribute("faculties", faculties);
//        //跳转页面
//        request.getRequestDispatcher("addAdmin.jsp").forward(request, response);
    }

    /**
     * 查询所有管理员
     *
     * @param request
     * @param response
     */
    private void showAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        SessionUtils.isSession(request, response);
        //调用方法，查找所有用户
        int curPage = Integer.parseInt(request.getParameter("curPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        List<Admin> admins = adminService.getAllAdmin(curPage, pageSize);
        int totalCount = adminService.getAllCount();

        Map map = new HashMap();
        map.put("count", totalCount);
        map.put("list", admins);
        map.put("curPage", curPage);
        //相应数据
        String jsonString = JSON.toJSONString(map);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(jsonString);
//        //把信息放入页面
//        request.setAttribute("admins", admins);
//        //跳转页面
//        request.getRequestDispatcher("showAdmin.jsp").forward(request, response);
    }

    /**
     * 管理员退出登录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void adminLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        HttpSession session = request.getSession();
        SessionUtils.isSession(request, response);
        //使得输入的用户信息失效
        session.removeAttribute("admin");
        response.getWriter().write("true");
//        message = "<script>alert('成功退出！');window.open('login.jsp','_self')</script>;";
//        //把信息放入页面
//        request.setAttribute("message", message);
//        //跳转页面
//        request.getRequestDispatcher("message.jsp").forward(request, response);
    }


    /**
     * 登录用户
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void admin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        HttpSession session = request.getSession();
        SessionUtils.isSession(request, response);

        Admin admin = (Admin) session.getAttribute("admin");
        String jsonString = JSON.toJSONString(admin);
        System.out.println(jsonString);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(jsonString);
//        //把信息放入页面
//        request.setAttribute("message", message);
//        //跳转页面
//        request.getRequestDispatcher("message.jsp").forward(request, response);
    }

    /**
     * 管理员登录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Session
        HttpSession session = request.getSession();
        //获取服务器保存的用户信息
        Map<String, String> user = (Map<String, String>) session.getAttribute("user");
        String adminName = user.get("userName");
        String passWord = user.get("passWord");
        //使得输入的用户信息失效
        session.removeAttribute("user");
        //获取管理员 账户
        Admin admin = adminService.getAdminByName(adminName);
        //判断账户是否为空
        if (admin != null) {
            //判断密码是否正确
            if (passWord.equals(admin.getPassword())) {
                //将用户放入session
                session.setAttribute("admin", admin);

                message = "<script>alert('登录成功！');window.open('project_of_html/index.html','_self')</script>";
            } else {
                message = "<script>alert('密码错误！');window.open('login.jsp','_self')</script>";
            }
        } else {
            message = "<script>alert('账户不存在！');window.open('login.jsp','_self')</script>";
        }
        //把信息放入页面
        request.setAttribute("message", message);
        //跳转页面
        request.getRequestDispatcher("message.jsp").forward(request, response);
    }
}
